package edu.kit.aifb.ldstream.learner.query;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;

import org.openrdf.model.BNode;

import edu.kit.aifb.ldstream.env.Environment;

public class BNodeCache implements Iterable<BNode>{

	private static int i = 0;
	
	private File bnodeCache = new File(Environment.BNODE_CACHE + i++);
	private BufferedWriter writer;
	
	public BNodeCache(){
		initFile();
		try {
			this.writer = new BufferedWriter(new FileWriter(this.bnodeCache));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void write(String value){
		try {
			this.writer.write(value);
			this.writer.write("\n");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void initFile(){
		if(this.bnodeCache.exists()){
			this.bnodeCache.delete();
		}
		try {
			this.bnodeCache.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
		this.bnodeCache.deleteOnExit();
	}
	
	public void closeWriter(){
		try {
			this.writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void close(){
		this.bnodeCache.delete();
	}

	@Override
	public Iterator<BNode> iterator() {
		return new BNodeCacheIterator(this.bnodeCache);
	}
}
